package cn.wzvtc.rbac_mp.service.impl;

import cn.wzvtc.rbac_mp.dao.UserMapper;
import cn.wzvtc.rbac_mp.dao.UserRoleMapper;
import cn.wzvtc.rbac_mp.dto.UserBO;
import cn.wzvtc.rbac_mp.entity.User;
import cn.wzvtc.rbac_mp.entity.UserRole;
import cn.wzvtc.rbac_mp.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author Shiwei Xu
 * @date 2020/5/20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

  @Autowired
  private UserRoleMapper userRoleMapper;

  @Transactional
  @Override
  public void addUser(UserBO userBO) {
    // 新增用户
    User user = new User();
    BeanUtils.copyProperties(userBO, user);
    this.save(user);

    // 新增角色用户关系
    addUserRole(user.getId(), userBO.getRoleIds());
  }

  @Transactional
  @Override
  public void updateUser(UserBO userBO) {
    // 更新用户
    User user = new User();
    BeanUtils.copyProperties(userBO, user);
    this.updateById(user);

    // 更新角色用户关系
    updateUserRole(user.getId(), userBO.getRoleIds());
  }

  private void addUserRole(Long userId, List<Long> roleIds) {
    // 用户没有一个用户角色的情况
    if (CollectionUtils.isEmpty(roleIds)) {
      return;
    }
    // 新增角色用户关系
    for (Long roleId : roleIds) {
      UserRole userRole = new UserRole();
      userRole.setUserId(userId);
      userRole.setRoleId(roleId);
      userRoleMapper.insert(userRole);
    }
  }

  private void updateUserRole(Long userId, List<Long> roleIds) {
    // 先删除原先的用户角色关系
    QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
    wrapper.eq("user_id", userId);
    userRoleMapper.delete(wrapper);

    // 建立新的用户角色管理
    addUserRole(userId, roleIds);
  }

  @Transactional
  @Override
  public void delete(List<Long> ids) {
    // 删除用户
    this.removeByIds(ids);
    // 删除用户角色关系
    QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
    wrapper.in("user_id", ids);
    userRoleMapper.delete(wrapper);
  }

}
